/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package evotingclient.votesending;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 *
 * @author Maciek
 */
public class PublicKeyHandler {
    public static final String file = "public.key";
    PublicKey publicKey;
    
    void loadPublicKey(String folder) throws NoSuchAlgorithmException, InvalidKeySpecException, FileNotFoundException, IOException{
        StringBuilder sb = new StringBuilder();
        if(folder==null || folder.equals("")){}
        else sb.append(folder).append(File.separatorChar);
        sb.append(file);
        
        byte[] pubKey = readBytesFromFile(sb.toString());
       // byte[] pubKey = publicKey.getEncoded();
        
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        publicKey = keyFactory.generatePublic(pubKeySpec);
 
    }
    
    byte[] readBytesFromFile(String selectedFile) throws FileNotFoundException, IOException {
            InputStream in = new FileInputStream(selectedFile);
            System.out.println(selectedFile + " rozmiar " + in.available());
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
        return data;

    }
    
     public byte[] rsaEncrypt(byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        PublicKey pubKey = publicKey;
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherData = cipher.doFinal(data);
        return cipherData;
    }
}
